
export function getParameterByName(name, url) {
  name = name.replace(/[\\[\]]/g, "\\$&")
  const regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
    results = regex.exec(url)
  if (!results) return null
  if (!results[2]) return ""
  return decodeURIComponent(results[2].replace(/\+/g, " "))
}

/**
 * 存储sessionStorageItem
 * @todo 应用调试完成后应考虑加密算法
 * @author ytl
 * @param key string
 * @param value Object|Array|String
 */
export function setSessionStorageItem(key, value) {
  let item = ""
  if (value instanceof Object) {
    item = JSON.stringify(value)
  } else {
    item = value
  }
  window.sessionStorage.setItem(key, item)
}

/**
 * 获取sessionStorageItem @todo 应用调试完成后应考虑解密算法
 * @author ytl
 * @param key string
 * @return {null}|string|Object
 */
export function getSessionStorageItem(key) {
  const value = window.sessionStorage.getItem(key)
  if (!value) {
    return null
  }
  try {
    return JSON.parse(value)
  } catch (err) {
    return value
  }
}

export function isWeChat() {
  const ua = navigator.userAgent.toLowerCase()
  // console.info(ua, "浏览器ua信息")
  return -1 !== ua.indexOf("micromessenger")
}

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = ""
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = encodeURIComponent(propName) + "="
    if (value !== null && typeof (value) !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && typeof (value[key]) !== "undefined") {
            const params = propName + "[" + key + "]"
            const subPart = encodeURIComponent(params) + "="
            result += subPart + encodeURIComponent(value[key]) + "&"
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&"
      }
    }
  }
  return result
}

export function getWeChatJsApiLink() {
  return /(Android)/i.test(navigator.userAgent) ? window.location.href.split("#")[0] : window.entryUrl
}

export function getPx(design, designWidth = 375) {
  let width = document.documentElement.getBoundingClientRect().width
  // 计算缩放比例
  let scale = width / designWidth
  // 获取实时尺寸
  return design * scale
}
